package com.learnyou.server.xingzuo.dao.repository.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.learnyou.server.xingzuo.dao.repository.entity.Behavior;
import com.learnyou.server.xingzuo.dao.repository.mapper.BehaviorMapper;
import com.learnyou.server.xingzuo.dao.repository.service.IBehaviorService;
import com.learnyou.server.xingzuo.dto.paramDTO.BehaviorQueryDTO;
import com.learnyou.server.xingzuo.dto.resultDTO.BehaviorResultDTO;
import com.learnyou.server.xingzuo.dto.resultDTO.TimeBehaviorDTO;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 行为清单 服务实现类
 * </p>
 *
 * @author heweifeng
 * @since 2023-11-23
 */
@Service
public class BehaviorServiceImpl extends ServiceImpl<BehaviorMapper, Behavior> implements IBehaviorService {

    @Override
    public BehaviorResultDTO behaviorsOfDay(BehaviorQueryDTO behaviorQueryDTO) {
        List<Behavior> list = lambdaQuery().between(Behavior::getStartTime, DateUtil.beginOfDay(behaviorQueryDTO.getBehaviorDate()), DateUtil.endOfDay(behaviorQueryDTO.getBehaviorDate()))
                .eq(Behavior::getCode, behaviorQueryDTO.getDeviceCode())
                .list();
        BehaviorResultDTO resultDTO = new BehaviorResultDTO();
        resultDTO.setBehaviorDate(behaviorQueryDTO.getBehaviorDate());
        resultDTO.setDetails(list.stream().map(this::buildResultDTO).collect(Collectors.toList()));
        return resultDTO;
    }

    @Override
    public void removeByBucketKey(String key) {
        lambdaUpdate().eq(Behavior::getBucketKey, key).remove();
    }

    @Override
    public List<Integer> getLastBehaviors(Long fileTime) {

        return lambdaQuery().select(Behavior::getBehavior).le(Behavior::getObjectTime, fileTime).orderByDesc(Behavior::getStartTime).last("limit 2").list()
                .stream().map(Behavior::getBehavior).collect(Collectors.toList());

    }

    private TimeBehaviorDTO buildResultDTO(Behavior behavior) {
        TimeBehaviorDTO resultDTO = new TimeBehaviorDTO();
        resultDTO.setBehavior(behavior.getBehavior());
        resultDTO.setTime(DateUtil.format(behavior.getStartTime(), "HH:mm"));
        return resultDTO;
    }
}
